package com.rainkaze.lifeharbor.tools.bingwallpaper.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.rainkaze.lifeharbor.R;
import com.rainkaze.lifeharbor.tools.bingwallpaper.model.WallpaperItem;
import java.util.List;
import java.util.Locale;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;


public class WallpaperAdapter extends RecyclerView.Adapter<WallpaperAdapter.WallpaperViewHolder> {

    private Context context;
    private List<WallpaperItem> wallpaperList;
    private final SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
    private final SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());


    public WallpaperAdapter(Context context, List<WallpaperItem> wallpaperList) {
        this.context = context;
        this.wallpaperList = wallpaperList;
    }

    @NonNull
    @Override
    public WallpaperViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_wallpaper_bing, parent, false);
        return new WallpaperViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull WallpaperViewHolder holder, int position) {
        WallpaperItem item = wallpaperList.get(position);

        holder.textViewTitle.setText(item.getTitle());
        holder.textViewCopyright.setText(item.getCopyright());

        // 格式化日期
        try {
            Date date = inputDateFormat.parse(item.getStartdate());
            if (date != null) {
                holder.textViewDate.setText(outputDateFormat.format(date));
            } else {
                holder.textViewDate.setText(item.getStartdate());
            }
        } catch (ParseException e) {
            holder.textViewDate.setText(item.getStartdate());
            Log.e("WallpaperAdapter", "日期解析失败: " + item.getStartdate(), e);
        }


        // 使用 Glide 加载图片
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.drawable.image_placeholder) // 占位图
                .error(R.drawable.image_error)       // 加载错误图
                .diskCacheStrategy(DiskCacheStrategy.ALL);

        Glide.with(context)
                .load(item.getFullImageUrl())
                .apply(requestOptions)
                .into(holder.imageViewWallpaper);

        // 点击图片打开链接
        holder.itemView.setOnClickListener(v -> {
            if (item.getCopyrightlink() != null && !item.getCopyrightlink().isEmpty()) {
                try {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getCopyrightlink()));
                    context.startActivity(browserIntent);
                } catch (Exception e) {
                    Log.e("WallpaperAdapter", "无法打开链接: " + item.getCopyrightlink(), e);
                    Toast.makeText(context, "无法打开链接", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return wallpaperList == null ? 0 : wallpaperList.size();
    }

    public void updateData(List<WallpaperItem> newWallpapers) {
        this.wallpaperList.clear();
        if (newWallpapers != null) {
            this.wallpaperList.addAll(newWallpapers);
        }
        notifyDataSetChanged();
    }

    public void addData(List<WallpaperItem> moreWallpapers) {
        if (moreWallpapers != null) {
            int oldSize = this.wallpaperList.size();
            this.wallpaperList.addAll(moreWallpapers);
            notifyItemRangeInserted(oldSize, moreWallpapers.size());
        }
    }


    static class WallpaperViewHolder extends RecyclerView.ViewHolder {
        ImageView imageViewWallpaper;
        TextView textViewTitle;
        TextView textViewCopyright;
        TextView textViewDate;

        public WallpaperViewHolder(@NonNull View itemView) {
            super(itemView);
            imageViewWallpaper = itemView.findViewById(R.id.imageView_wallpaper_item);
            textViewTitle = itemView.findViewById(R.id.textView_wallpaper_title_item);
            textViewCopyright = itemView.findViewById(R.id.textView_wallpaper_copyright_item);
            textViewDate = itemView.findViewById(R.id.textView_wallpaper_date_item);
        }
    }
}